// pages/course_detail/index.js
import {navTo,navToTab,onInput,onClick,showText} from '../../utils/reuse'
import{getCourseDetail,getUserTime,getUserSubmitYy} from '../../api/index'
import {formatTime} from '../../utils/util'
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';
import {baseURL} from '../../utils/request'
import drawQrcode from '../../utils/weapp.qrcode.esm.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    width:wx.getSystemInfoSync().windowWidth,
    subscribeShow:false,
    subscribeShow1:false,

    course_detail:{},
    shop_detail:{},
    class_cash:{},
    point:false,
    
    course_show:false,
    // 营业时间
    business_show:false,
    currentDate1: '8:00',
    currentDate2: '18:00',
    minHour: 0,
    maxHour: 24,

    coachList: [],
    makeList: [],

    yy_show:false,
    jl_show:false,
    time_show:false,

    currentDate: new Date().getTime(),
    minDate: new Date().getTime(),
    formatter(type, value) {
      if (type === 'year') {
        return `${value}年`;
      }
      if (type === 'month') {
        return `${value}月`;
      }
      return value;
    },
    zlist:[],
    form:{
      jl:'',
      yysj:'',
      time:''
    },
  },

  submit(){
    var jl = this.data.zlist.jl.find(item => {
      if(this.data.form.jl === item.nickname){
        return item
      }
    })
    var sj = this.data.zlist.time.find(item => {
      if(this.data.form.yysj === item.starttime  + '~' + item.endtime){
        return item
      }
    })
    var obj = {
      uid:wx.getStorageSync('uid'),
      class_id:this.data.class_cash.class_id,
      time_id:sj.id,
      admin_id:jl.id,
      date:this.data.currentDate
    }
    getUserSubmitYy(obj).then(res=>{
      if(res.sta == 1){
        showText(res.msg,1)
        wx.requestSubscribeMessage({
          tmplIds: ['Iye-QLfWDtLd73Zy08OfiJjV1IQS9avOsjSVIxC8C6w'],
          success (res) {
            showText('消息订阅成功',1)
            setTimeout(() => {
              wx.navigateBack()
            }, 1000);
          },
          fail(res){
            showText('消息订阅失败',2)
          }
        })
      }else if(res.msg == '已预约'){
        showText(res.msg,2)
        setTimeout(() => {
          wx.navigateBack()
        }, 1000);
      }else{
        showText(res.msg,2)
      }
    })


  },
  jlFn(){
    this.setData({
      jl_show:true
    })
  },
  yydsFn(){
    this.setData({
      yy_show:true
    })
  },
  cancel(e){
    this.setData({
      form:{
        jl:'',
        yysj:'',
        time:''
      },
      course_show:false
    })
  },
  yyFn(e){
    var obj = {
      class_id:e.currentTarget.dataset.id
    }
    getUserTime(obj).then(res=>{
      if(res.sta == 1){
        this.setData({
          zlist:res
        })
        if(res.jl.length >= 1){
          var arr = []
          res.jl.forEach(item=>{
            arr.push(item.nickname)
          })
          this.setData({
            coachList:arr
          })
        }
        if(res.time.length >= 1){
          var arr = []
          res.time.forEach(item=>{
            arr.push(item.starttime + '~' +item.endtime)
          })
          this.setData({
            makeList:arr
          })
        }
        this.setData({
          'form.jl':this.data.coachList[0],
          'form.yysj':this.data.makeList[0],
        })
      }
    })
    this.setData({
      course_show:true
    })
    
  },
  jlonChange(event){
    const { picker, value, index } = event.detail;
    this.setData({
      'form.jl':value
    })
  },
  yyonChange(event){
    const { picker, value, index } = event.detail;
    this.setData({
      'form.yysj':value
    })
  },
  qrClick(e){
    var that = this
    var id = e.currentTarget.dataset.id
    if(id){
      setTimeout(() => {
        const query = wx.createSelectorQuery()
        query.select('#myQrcode')
        .fields({
            node: true,
            size: true
        })
        .exec((res) => {
            var canvas = res[0].node
  
            // 调用方法drawQrcode生成二维码
            drawQrcode({
                canvas: canvas,
                canvasId: 'myQrcode',
                width: 260,
                padding: 30,
                background: '#ffffff',
                foreground: '#000000',
                text: `{"uid":${wx.getStorageSync('uid')},"status":${1},"course_id":${id},"current_time":${new Date().getTime()}}`,
            })
            // 获取临时路径（得到之后，想干嘛就干嘛了）
            wx.canvasToTempFilePath({
                canvasId: 'myQrcode',
                canvas: canvas,
                x: 0,
                y: 0,
                width: 260,
                height: 260,
                destWidth: 260,
                destHeight: 260,
                success(res) {
                  that.setData({
                    subscribeShow:true
                  })
                },
                fail(res) {
                    console.error(res)
                }
            })
        })
      }, 1000);

    }
  },

  click(e){
    onClick(e,this)
  },
  change(e){
    onInput(e,this)
  },
  input(key){
    onInput(key,this)
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    var id = options.id
    if(id){
      var obj = {
        uid:wx.getStorageSync('uid'),
        id
      }
      getCourseDetail(obj).then(res=>{
         
        if(res.sta == 1){
          if(res.class.images){
            var arr1 = []
            res.class.images = res.class.images.split(',')
            res.class.images.forEach(item=>{
              arr1.push(baseURL + item)
            })
            res.class.images = arr1
          }
          if(res.shop.images){
            var arr1 = []
            res.shop.images = res.shop.images.split(',')
            res.shop.images.forEach(item=>{
              arr1.push(baseURL + item)
            })
            res.shop.images = arr1
          }
          that.setData({
            course_detail:res.class,
            shop_detail:res.shop,
            class_cash:res.class_cash!='undefined'?res.class_cash:false,
            point:res.point!='undefined'?res.point:false,
          })
          
        }else{
          showText('数据获取失败！',2)
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})